package com.qingke.ocr.servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.qingke.ocr.pojo.OCRMessage;

@WebServlet("/receive")
public class ReceiveServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ReceiveServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getSession().getAttribute("nick")==null){
			return ;
		}
		if(request.getSession().getAttribute("logged")==null||(Integer)request.getSession().getAttribute("logged")!=1){
			return ;
		}
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		ServletContext sc= getServletContext();
		if(sc.getAttribute("list")==null){
			sc.setAttribute("list",new ArrayList<OCRMessage>());
		}
		if(sc.getAttribute("map")==null){
			sc.setAttribute("map",new HashMap<String,Long>());
		}
		@SuppressWarnings("unchecked")
		List<OCRMessage> list=(List<OCRMessage>)sc.getAttribute("list");
		@SuppressWarnings("unchecked")
		Map<String,Long> map=(Map<String,Long>)sc.getAttribute("map");
		
		
		String nick=request.getParameter("nickname");
		String message=request.getParameter("message");
		long currentTime=System.currentTimeMillis();
		
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		String timeStr=sdf.format(new Date(currentTime));
		OCRMessage ocrm=new OCRMessage();
		ocrm.setNick(nick);
		ocrm.setMessage(message);
		ocrm.setTime(currentTime);
		ocrm.setTimeStr(timeStr);
		list.add(ocrm);
		
		map.put(nick, currentTime);
		
		if(list.size()>1000){
			for(int i=0;i<900;i++ ){
				list.remove(0);
			}
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
